package smyx

import (
	"log"
	"net/http"
)

// HandlerFunc http请求handler
type HandlerFunc func(c *Context)

// Server 实现 ServeHTTP 接口
type Server struct {
	router *router
}

// Create 构造器
func Create() *Server {
	return &Server{router: newRouter()}
}

// GET GET请求
func (server *Server) GET(pattern string, handler HandlerFunc) {
	server.addRoute("GET", pattern, handler)
}

// POST POST请求
func (server *Server) POST(pattern string, handler HandlerFunc) {
	server.addRoute("POST", pattern, handler)
}

// Start 启动 http server
func (server *Server) Start(addr string) (err error) {
	return http.ListenAndServe(addr, server)
}

func (server *Server) ServeHTTP(w http.ResponseWriter, req *http.Request) {
	c := newContext(w, req)
	server.router.handle(c)
}

// addRoute 添加路由
func (server *Server) addRoute(method string, pattern string, handler HandlerFunc) {
	log.Printf("Route %4s - %s", method, pattern)
	server.router.addRoute(method, pattern, handler)
}
